// testing
var everyTrailDistance = 30;
var recordID;
var maxrows = 50;
var myLocation;
var watchId;
var trackOn = false;
var geoCount = 0;
var myLat = 41.99;
var myLon = -72.88;
var zoom = 8;
var autoSearch = true;
var firstTime = true;	
var latlng, center, geocoder;
var myLocations = [];
var map, map2;
var points;
var point;
var markerArray = [];
var markerArray2 = [];
var marker;
var html, wikiHtml, placeHtml, helpHtml = '';
var currentMarkerIndex = -1;
var centerMarker;
var points2 = [];
var NOAAWeather, NOAAWeatherText;
var icons = [
	'http://labs.google.com/ridefinder/images/mm_20_blue.png',
	'http://labs.google.com/ridefinder/images/mm_20_red.png',
	'http://maps.google.com/mapfiles/ms/micons/yellow.png'
//	'http://maps.google.com/mapfiles/ms/micons/blue.png',
//	'http://maps.google.com/mapfiles/ms/micons/red.png',
];
var llb; //latlngbounds
var searchControl;
var street, city, county, state, state_abbr, zip, country = '';
var lat, lon = 0;

google.load('search', '1.0');
google.setOnLoadCallback(searchLoad, true);

$(document).ready(function() {
	initialize();
});

function initialize(){
	debugMessage('initialize()');
	recordID = window.location.hash;
	if($.cookie('myLat')!==null) {myLat = $.cookie('myLat');}
	if($.cookie('myLon')!==null) {myLon = $.cookie('myLon');}
	if($.cookie('zoom')!==null) {zoom = 1 * $.cookie('zoom');}
	setupMap();
	setupMap2();

	$("#locateButton").click(function () {
		searchMap();
	});
	$(".gs-snippet").live('dblclick', function(){
//			alert('dblclick');
		var url = $(this).prev();
		var href = encodeURI(url[0].firstChild.href);
		href = href.replace('http://','');
		var homepage = $(this).next().attr('innerHTML');
		addLink(href, homepage, lat, lon);
	});
	
	$("#button2").click(function(){
		alert('button2 clicked');
	});
	
//	$('#tabs1').tabs({ fx: { opacity: 'toggle' } });
//	$('#search').tabs({ fx: { opacity: 'toggle' } });
//	$("#dropzone").sortable({connectWith: '#itinerary'});
//	$('#itinerary').sortable({ connectWith: '#dropzone' });
/*	$('#map-window').dialog({
		position: 'right',
		width: '400px',
		resizable: false,
		closeText: 'hide'
	}	
	); */
//	$('#itinerary').draggable();

	setupHelp();

}
function addLink( linkURI, homepage){
	helpOptions = {
		position: 'center',
		width: '400px'
	};

	$.ajax({
		url: '../addlink.php',
		dateType: 'json',
		type: 'POST',
		data: {
			lat: lat,
			lon: lon,
			state: state,
			county: county,
			city: city,
			linkURI: linkURI,
			homepage: homepage
		},
		success: function(data) {
			$('#helpMapText').html(data);
			$('#helpMapText').dialog(helpOptions);
		
		},
		failure: function(){
		}
	});
};

	
	

function searchMap(){
	debugMessage('searchMap()');
	var location =  $('#locateText').attr('value');
	if(location!=='') {
		geocoder.geocode(
			{
				'address' : location
			},
			function(results,status){
				if(status==google.maps.GeocoderStatus.OK) {
					ll = results[0].geometry.location;
					map.setCenter(ll);
					myLat = ll.lat();
					myLon = ll.lng();
					getPlaces();
				}
				else {
//					alert('issue with geocoder, status='+status);
				}
			}
		);	
	}
} //searchMap()

function getPlace(id){
	debugMessage('getPlace('+id+')');
	$.ajax({
			url: '../getplace.php',
		data: {
			table:'boats',
			recordID: id
			},
	  	success: function(data) {
			debugMessage('getPlace - success');
			var points = eval(data);
			var tp = points.results[0];
			myLat = tp.lat;
			myLon = tp.lon;	
			name = tp.name;
			latlng = new google.maps.LatLng(myLat, myLon);
			map.setCenter(latlng);
			window.location.hash = id;
			getPlaces();
		}
	});
}  //getPlace()

function getPlaces(){
	debugMessage('getPlaces()');
//	llb = new google.maps.LatLngBounds(map.getCenter());
//	$('#tabs').tabs('select',0);
	bounds = map.getBounds();
//	center = map.getCenter();
	sw = bounds.getSouthWest();
	ne = bounds.getNorthEast();
	points2 = [];
	$.ajax({
		url: '../getplaces.php',
		data: {
			table:'boats',
//			ctrlat: center.lat(),
//			ctrlon: center.lng(),
			ctrlat: myLat,
			ctrlon: myLon,
			swlat: sw.lat(),
			swlon: sw.lng(),
			nelat: ne.lat(),
			nelon: ne.lng(),
			count: maxrows,
			type:'%' //wildcard
			},
	  	success: function(data) {
	  		debugMessage('getPlaces - success');
			var points = eval(data);
			var dataHtml = '<table>';
			if(points.total>0){
			clearMarkers(markerArray);
			currentMarkerIndex = -1;
			for(i=0;i<points.total;i++){
				var tp = points.results[i];
				ix = tp.id;
				points2[ix] = tp;
				points2[ix].markerID = i;
//				var js = '<a  id="markers'+markerArray.length+'" href="#">'+tp.name+'</a>';
				dataHtml += '<tr><td><a class="displayPoint" id="markers'+markerArray.length+'" href="#">'+tp.name+'</a></td></tr>';
//				js = '<td>';
//				if(tp.town) js 	 += tp.town + '; ';
//				if(tp.state) js  += tp.state + '; ';
//				if(tp.type) js 	 += tp.type + '; ' ;
//				if(tp.source) js += tp.source ;
//				js += '</td></tr>';
//				dataHtml += js;
				var marker = createMarker(map, tp.name, tp.lat, tp.lon, 0, markerArray.length, true, tp);
				if(i==0){
					displayPoint(0);
				}
//				llb.extend(new google.maps.LatLng(tp.lat,tp.lon));			
			}
			dataHtml += '</table>';
			$('#data').html(dataHtml);
			
			$(".displayPoint").click(function(event){
				var ev = event.currentTarget;
				var id = ev.id.substring(7,99);
				var marker = markerArray[id];
				google.maps.event.trigger(marker,'click');
			});			
	
			}
		}

	});
} // getPlaces()

function displayPoint(markerIndex){
	debugMessage('displayPoint()');
	$('#everyTrailTab').hide();
	$('#place').html('');
	$('#weather').html('');

	html = '';
	wikiHtml = '';
	placeHtml = '';
	street = '';
	city = '';
	county = '';
	state_abbr = '';
	state = '';
	zip = '';
	country = '';

	var m = markerArray[markerIndex];
	var pt = m.getPosition();
	lat = pt.lat();
	lon = pt.lng();
	var latlon = lat + ', ' + lon;
	var ll = 'lat='+lat+'&lng='+lon;
	var latlng = new google.maps.LatLng(lat, lon);
	var id = m.details.id;
	recordID = m.details.id;
	var name = m.title;
	var url = m.details.url;
//	var town = m.details.town;
	state = m.details.state;
	var distance = m.details.distance;
	var source = m.details.source;
	var type = m.details.type;
	var description = m.details.description;
	$('#placename').html(name);
//	$('#itinerary').append('<div id="'+recordID+'"><li><a href="http://parkandpaddle.com/index9.php#' + recordID + '">' + name + '</a> ' + state + '</li></div>');
//	$('#'+recordID).draggable();
	var droidDirections 	= "geo:"+latlon+"?q="+latlon; 
	var geoNamesWiki 	= 'http://ws.geonames.org/findNearbyWikipediaJSON?maxRows=5&'+ll;
	var NOAAQuickForecast   = 'http://forecast.weather.gov/afm/PointClick.php?lat='+lat+'&lon='+lon;
	NOAAWeather 		= 'http://forecast.weather.gov/MapClick.php?textField1='+lat+'&textField2='+lon;
	NOAAWeatherText 	= 'http://forecast.weather.gov/MapClick.php?textField1='+lat+'&textField2='+lon+'&TextType=1';
	var googleSearch 	= 'http://google.com/search?q=%27'+name+'%27%20'+state+'%20paddling';
	var NOAATideLinks	= 'http://tidesandcurrents.noaa.gov/tide_predictions.shtml?type=Tide+Predictions&searchfor='+lat+'%2C+'+lon;
	var zipcode = null;
//	setupHelp();
	placeHtml = '';
	href = 'http://google.com/maps?q='+latlng;
	placeHtml += '<table><tr>';
	if(url) placeHtml += '<td><button type="button" onclick="window.open('+"'"+url+"'"+')">source</button></td>';
	placeHtml += '<td><button type="button" onclick="window.open('+"'"+href+"'"+')">google map</button></td>';
	placeHtml += '<td><button type="button" onclick="window.open('+"'"+NOAATideLinks+"'"+')">NOAA Tide Tables</button></td>';
	placeHtml += '</tr></table>';
	placeHtml += '<table>';
	placeHtml += tablePair('id',recordID);
	placeHtml += tablePair('type',type);
	placeHtml += tablePair('distance',distance+' miles');
	placeHtml += tablePair('lat, lon',latlon);
//	placeHtml += tablePair('description',description);		
	
	marker2 = createMarker(map2, name, lat, lon, 2, 1, false, 'asdf');
	if(currentMarkerIndex>-1){
		markerArray[currentMarkerIndex].setIcon(icons[0]);
		markerArray[currentMarkerIndex].setAnimation(null);
	}
		google.maps.event.addListener(marker2, 'click', function() {
//			debugMessage('marker listener: click');
			alert('click'+ name +': ' +lat+','+lon);
		});
	currentMarkerIndex = markerIndex;
	markerArray[markerIndex].setIcon(icons[2]);
//	markerArray[markerIndex].setAnimation(google.maps.Animation.BOUNCE);
//	markerArray[markerIndex].setZIndex(9999);
	marker2.setMap(map2);
	if($('#map2').css('visibility')=='hidden'){
		$('#map2').css('visibility','visible');
//		$('#place').css('visibility','visible');
	}
	ctr = new google.maps.LatLng(lat,lon);
//	map.panTo(ctr);
//	map2.panTo(ctr); 
	map.setCenter(ctr);
	map2.setCenter(ctr);
google.maps.event.trigger(map, 'resize');
	placeHtml += '</table>';
//  	$('#place').html(placeHtml);
  	window.location.hash = recordID;
  	getReverseGeocode(latlng);
//  	getWikipedia();
//  	getEveryTrail();
  	getWeather();  		
}


function createMarker(map, name, lat, lon, iconIndex, arrayIndex, saveMarker, pointDetails){
//	debugMessage('createMarker()');
	var point = new google.maps.LatLng(lat, lon);
	var marker = new google.maps.Marker({
		position: 	point,
		map: 		map,
		icon: 		icons[iconIndex],
		title: 		name,
		details:	pointDetails
	});	
	marker.setMap(map);
	if(saveMarker) {
		markerArray.push(marker);
		google.maps.event.addListener(marker, 'click', function() {
//			debugMessage('marker listener: click');
			displayPoint(arrayIndex);
//			if(marker.getAnimation(google.maps.Animation.BOUNCE)){} 
//			else {marker.setAnimation(google.maps.Animation.BOUNCE);};
		});
	};
	return marker;
} // displayPoint()

function imagePop(url){
	helpOptions = {
		position: 'top',
		width: '800px'
	};
//	html = '<img src="'+url+'" />';
	html = '<img src="'+url+'" width="98%"/>';
	$('#helpMapText').html(html);
	$('#helpMapText').dialog(helpOptions);

}
function kmlOverlay(url){
	var kmlOverlay = new google.maps.KmlLayer(url, {
		map: map
	});	
//	var kmlOverlay2 = new google.maps.KmlLayer(url, {
//		map: map2
//	});	
}

function clearMarkers(markers) {
	debugMessage('clearMarkers()');
	if (markers) {
		for (i in markers) {
			markers[i].setMap(null);
		}
	markers.length = 0;
	}
}

function tablePairOld(label, value){
//	debugMessage('tablePair()');
	if(value) {
		html += '<tr><td><b>'+label+':</b></td><td>'+value+'</td></tr>';
	} 
}

function tablePair(label, value){
//	debugMessage('tablePair()');
	if(value) {
		return('<tr><td><b>'+label+':</b></td><td>'+value+'</td></tr>');
	} 
}

function buttonGet(label, href){
//	debugMessage('buttonAdd()');
	if(href){
//		return( '<button type="button" onclick="window.open('+"'"+href+"'"+')">'+label+'</button>');
		return('<b><a href="'+href+'" target="_blank">' + label + '</a></b>');
	}
}

function buttonAdd(label, href){
//	debugMessage('buttonAdd()');
	if(href){
//		html +=  '<button type="button" onclick="window.open('+"'"+href+"'"+')">'+label+'</button>';
		return( '<b><a href="'+href+'" target="_blank">' + label + '</a></b>');
	}
}

function linkAdd(tableLabel,href, linkLabel){
//	debugMessage('linkAdd()');
	if(href){
		html += '<tr><td><b>'+tableLabel+':</b></td><td><a href="'+href+'" target="_blank">'+linkLabel+'</a></td></tr>';
	}
}

function getCookies(){
	debugMessage('getCookies');
	if($.cookie('myLat')!==null) {myLat = $.cookie('myLat');}
	if($.cookie('myLon')!==null) {myLon = $.cookie('myLon');}
	if($.cookie('zoom')!==null) {zoom = 1 * $.cookie('zoom');}
}


function saveCookies(){
	debugMessage('saveCookies');
	$.cookie('myLat',map.getCenter().lat(),{expires:7});
	$.cookie('myLon',map.getCenter().lng(),{expires:7});
	$.cookie('zoom',map.getZoom(),{expires:7});
}

function searchLoad(){
		searchControl = new google.search.SearchControl();
		var options = new google.search.SearcherOptions();
		options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
		searchControl.addSearcher(new google.search.WebSearch(), options);
//		searchControl.addSearcher(new google.search.LocalSearch(), options);
		searchControl.draw(document.getElementById("searchcontrol"));
} // searchLoad()

function searchLoad2(){
    customSearchControl = new google.search.CustomSearchControl('018219830395631584804:mcava1tzldy');
    customSearchControl.setResultSetSize(google.search.Search.SMALL_RESULTSET);
    customSearchControl.draw('searchcontrol');
}


function setupHelp(){
	helpOptions = {
		position: 'center',
		width: '400px'
	};
	$('.helpText').hide();
	$('#placename').click(		
		function(){
			helpHtml = '';
			helpHtml += '<p><b>center</b> map using mouse - when you see the little hand with all fingers spread, hold down the left button and drag map around.</p>';
			helpHtml += '<p><i>if the hand is pointing with a <b>finger</b>, then you are on a <b>hot spot</b> - either a map control, or a marker, or some other doodad that will behave differently.  Watch out for the pointing figer, the map will not move around if the finger is up.</i></p>';
			helpHtml += '<p>when done dragging, a <b>single left click</b> anywhere on the map itself (other than hot-spots - see above) to update display with nearest boat launches.</p>';
			helpHtml += '<p>you can also <b>type in an address</b> and press <b>"locate"</b>, the map will re-center and re-load nearest boat launches.</p>';
			helpHtml += '<p>a <b>red marker</b> indicates the currently highlighted launch - with details on the right part of the screen.</p>'; 
			helpHtml += '<p>click on any <b>blue marker</b> - and in this case, the pointy finger is a good thing, indicating that you are hovering over a hot spot - to highlight that location. or, click on one of the <b>names</b> below.</p>';
			helpHtml += '<p>if you have trouble, try zooming out a bit and re-click on map.  Also, data is not available in all regions, try east coast for now ;) </p>';
			helpHtml += '<p>if you have a mouse with a wheel in the middle, try rolling it - the map should zoom in and out as you roll the wheel.  If you do not have a wheel, use the + and - symbols on the map to zoom in and out.</p>';
			$('#helpMapText').html(helpHtml);
//			$('#helpMapText').toggle('slow');
			$('#helpMapText').dialog(helpOptions);
		},
		function(){
			$('#helpMapText').dialog('close');
		}
	);
	
	$('#localMapTitle').hover(
		function(){
			helpHtml = '';
			helpHtml += '<p>you should have a <b>satellite view</b> of the boat launch and local <b>weather report</b> below the map.</p>';
			helpHtml += '<p>the map can be changed through a number of <b>controls</b> (little boxes, +/- sign, human figure, etc), click on some and see what happens.</p>';
			helpHtml += '<p>if you <b>get lost</b>, go back to the search map (on left) and re-click on the red marker, it will reset your center map.</p>';
			helpHtml += '<p>the <b>detail</b> link will take you to the NOAA site for more detailed weather.</p>';
			$('#helpMap2Text').html(helpHtml);
			$('#helpMap2Text').dialog(helpOptions);
		},
		function(){
			$('#helpMap2Text').dialog('close');
		}
	);

	$('#googleSearchTitle').hover(
		function(){
//			$('#helpMapText').toggle('slow');
	helpHtml = '';
	helpHtml += '<p>below are <b>google search</b> results based on this location plus the keywords <b>"paddle OR paddling"</b></p>';
	helpHtml += '<p>these should be the exact same results you would get if you typed in the name of this boat launch plus the state abbreviation plus the "paddle OR paddling" keyword phrase into a google search window.</p>';
	$('#helpGoogleSearchText').html(helpHtml);
			$('#helpGoogleSearchText').dialog(helpOptions);

		},
		function(){
			$('#helpGoogleSearchText').dialog('close');
		}
	);
}

function debugMessage(msg) {
	if(false){
		$('#debugMessage').append(msg+'<br>');
	}
}	

function setupMap(){
	debugMessage('setupMap()');
	latlng = new google.maps.LatLng(myLat, myLon);
	center = latlng;
	geocoder = new google.maps.Geocoder();

	var myOptions = {
		zoom: zoom,
		center: center,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		navigationControl: true,
		streetViewControl: false,
		mapTypeControl: false,
		navigationControlOptions: {
			position: google.maps.ControlPosition.TOP_LEFT
		}
	};
 
	map = new google.maps.Map(document.getElementById("map"), myOptions);

	google.maps.event.addListener(map, 'click', function(a){
		debugMessage('map listener - click');
		myLat = a.latLng.lat();
		myLon = a.latLng.lng();
		getPlaces();
	});
	google.maps.event.addListener(map, 'idle', function(){
		debugMessage('map listener - idle');
		if(autoSearch){
			debugMessage('map listener - idle - autoSearch');
			autoSearch = false;
//			getPlaces();		
		};
		saveCookies();
		google.maps.event.trigger(map, 'resize');
	});
	google.maps.event.addListener(map, 'tilesloaded', function(){
		debugMessage('map: tiles loaded');
		if(firstTime){
			debugMessage('map: tiles loaded - first time');
			firstTime = false;
			if(recordID) {
				debugMessage('recordID '+ recordID + ' detected');
				recordID = recordID.substr(1)*1;
				getPlace(recordID);
			} else {
				getPlaces();
			}
		};
	});
}		// setupMap()

	
	
	
function setupMap2() {
	debugMessage('setupMap2()');
	var myOptions2 = {
			zoom: 19,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.SATELLITE,
			navigationControl: true,
			navigationControlOptions: {
				position: google.maps.ControlPosition.TOP_LEFT
			},
			scaleControl: false,
			scaleControlOptions: {
				position: google.maps.ControlPosition.LEFT
			},
			streetViewControl: false
		};
		map2 = new google.maps.Map(document.getElementById("map2"), myOptions2);
//		google.maps.event.trigger(map2, 'resize');
/*
		google.maps.event.addListener(map,'dragend',function(){
			map2.setCenter(map.getCenter());	
		});
		google.maps.event.addListener(map2,'rightclick',function(latlng){
			alert('right click at ' + latlng.toString());	
		});
*/
}
/* Wikipedia */
	function getWikipedia() {
	 $.ajax({
		url: 'http://ws.geonames.org/findNearbyWikipediaJSON',
		data: {
			lat: lat,
			lng: lon,
			maxRows: 10
			},
	  	success: function(data) {
	  		wikiHtml ='<h3>Wikipedia</h3>';
			for (i=0;i<data.geonames.length;i++) {
				wikiHtml += buttonAdd(data.geonames[i].title, 'http://'+data.geonames[i].wikipediaUrl);
				wikiHtml += '<p>' + data.geonames[i].summary + '</p>';
			}
			$('#wikiPlaces').html(wikiHtml);
		}
	});
};

/* EveryTrail */
	function getEveryTrail() {
	$.ajax({
		url: 'getEveryTrail.php',
		data: {
			lat: lat,
			lon: lon,
			distance: 15
			},
	  	success: function(data) {
	  		if(data=='') {
	  			$('#everyTrailTab').hide();
	  		} else {
	  			$('#everyTrailTab').show();
	  			$('#everyTrail').html(data);
	  		}
		}
	});
	};

/* Weather */
	function getWeather() {
	$.ajax({
		url: 'getweather.php',
		data: {
			lat: lat,
			lon: lon
			},
	  	success: function(weatherHtml) {
	  		var button = buttonGet('NOAA Weather Report Details',NOAAWeather);
  			$('#weather').html(button + '<br>'+weatherHtml+'<br>');
		},
		failure: function(){
	  		var button = buttonGet('NOAA Weather Report Details',NOAAWeather);
			$('#weather').html(buttonGet+'<br>problem loading weather');
		}
	});
	};

function getLinks(state){
	$.ajax({
		url: 'getlinks.php',
		type: 'POST',
		data: {
			state: state
			},
	  	success: function(data) {
			var links = eval(data);
			var dataHtml = '<table>';
			if(links.total>0){
				for(i=0;i<links.total;i++){
					var tp = links.results[i];
					dataHtml += '<tr>';
					dataHtml += '<td>'+tp.state+'</td>';
					dataHtml += '<td width="50%"><a href="'+tp.url+'" target="_blank">'+tp.name+'</a></td>';
					dataHtml += '<td>'+tp.description+'</td>';
					dataHtml += '</tr>';
				}
				dataHtml += '</table>';
				$('#links').html(dataHtml);
			}
		}
	});
} 
//getLinks()

/* Reverse Geocode via Google */

function getReverseGeocode(latlng){
	geocoder.geocode(
		{
		'location' : latlng
		},
		function(results,status){
			if(status==google.maps.GeocoderStatus.OK) {
				for (i in results[0].address_components) {
					var t = results[0].address_components[i];
					for (x in t.types){
//c						placeHtml += '<br>'+t.types[x]+': '+t.long_name; // shows all returned values from reverse geocode
						if(t.types[x]=='administrative_area_level_1'){
							state = t.long_name;
							state_abbr = t.short_name;
							getLinks(state_abbr);
						}
						if(t.types[x]=='administrative_area_level_2'){
							county = t.long_name;
						}
						if(t.types[x]=='locality'){
							city = t.long_name;
						}
						if(t.types[x]=='postal_code'){
							zip = t.long_name;
//			  				placeHtml += buttonAdd('tides','http://tidesandcurrents.noaa.gov/geo.shtml?location='+zip);
						}
						if(t.types[x]=='route'){
							street = t.long_name;
						}
						if(t.types[x]=='county'){
							county = t.long_name;
						}
						if(t.types[x]=='country'){
							country = t.long_name;
						}
						
					}
				}
  				placeHtml += buttonAdd('tides','http://tidesandcurrents.noaa.gov/geo.shtml?location='+zip);
  				placeHtml += '<br>';
				placeHtml += '<table>';
				placeHtml += tablePair('street',street);
				placeHtml += tablePair('city',city);
				placeHtml += tablePair('county',county);
				placeHtml += tablePair('state',state); // overrides database
				placeHtml += tablePair('state abbr',state_abbr); // overrides database
				placeHtml += tablePair('country',country);
				placeHtml += tablePair('zip',zip);
//				linkAdd('wiki','http://www.jimdevoe.com/mediawiki-1.15.1/index.php5?title='+state_abbr,'page='+state_abbr);
				placeHtml += '</table>';
				$('#place').html(placeHtml);
//				searchString = 'paddle';
				searchString = '';
				if(name) searchString += ' '+name;
				if(city) searchString += ' '+city;
//				if(county) searchString += ' '+county;
				if(state) searchString += ' '+state;
//				searchControl.execute(searchString);
			}
			else {
				$('#place').html(placeHtml);
//				searchControl.execute('+"'+name+'" '+state);
			}
		}
	);
}

